package com.itheima.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    /**
     * 获取所有部门信息, 封装为List<Dept>返回
     * @return
     */
    @Override
    public List<Dept> getDepts() {
        return deptMapper.getDepts();
    }

    /**
     * 根据部门 id 删除部门信息
     * 开启事务处理
     * 删除部门的同时删除该部门的员工
     * 且设置回滚异常为所有异常
     * 默认只有运行时异常才会回滚
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDeptById(Integer id) {
        try {
            deptMapper.deleteDeptById(id);
            empMapper.deleteEmpByDeptId(id);
        } finally {
            DeptLog log = new DeptLog();
            log.setCreateTime(LocalDateTime.now());
            log.setDescription("执行了删除部门操作 部门id为：" + id);
            deptLogService.insert(log);
        }
    }

    @Override
    public void addDept(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.addDept(dept);
    }

    @Override
    public Dept getDeptById(Integer id) {
        return deptMapper.getDeptById(id);
    }

    @Override
    public void updateDept(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);
    }
}
